<!-- 处理工单2 -->
<template>
	<view class="container">
		<view class="tabs">
			<van-tabs :active="active" swipe-threshold="3" title-active-color="#3F7CFF" color="transparent"
				@click="onClick">
				<!-- 遍历 tabsList -->
				<van-tab v-for="(tabs, index) in tabsList" :key="index" :title="tabs.name" :name="tabs.name">
					<view class="itemMain" v-for="(item, itemIndex) in tabs.workorderReportItemList" :key="itemIndex">
						<!-- 0 单行文本框 -->
						<view class="singlelineInput" v-if="item.type === 0">
							<view class="inputTitle">{{ item.name }}</view>
							<input class="input-class" :data-id="item.id" :disabled="disabled" :value="item.value"
								@input="bindSinglelineInput" placeholder="请输入" />
						</view>
						<!-- 1 多行文本框 -->
						<view class="multilineInput" v-if="item.type === 1">
							<view class="txt">{{ item.name }}</view>
							<uv-textarea class="areas" placeholder="请输入" v-model="item.value" :disabled="disabled"
								@input="textareaInputs">
							</uv-textarea>
						</view>
						<!-- 2 说明文字 -->
						<view class="multilineInput" v-if="item.type === 2">
							<view class="txt">{{ item.name }}</view>
							<uv-textarea class="areas" placeholder="请输入" v-model="item.value" :disabled="disabled"
								@input="textareaInputs">
							</uv-textarea>
						</view>
						<!-- 3 开关选项 -->
						<view class="switch" v-if="item.type === 3">
							<text>{{ item.name }}</text>
							<uv-switch 
								:v-model="item.value === '' ? false : item.value || item.value === 'true' ? true : false"
								:disabled="disabled" @change="switchChange" />
						</view>
						<!-- 4 图片拍照 -->
						<view class="img" v-if="item.type === 4 && state != 5">
							<view class="txt">{{ item.name }}</view>
							<view class="upload">
								<image-upload :uploadId="item.id" :disabled="disabled" :fileList="fileList"
									@returnAvatar="returnAvatar" />
							</view>
						</view>
						<view class="img" v-if="item.type === 4 && state == 5">
							<view class="txt">{{ item.name }}</view>
							<view class="upload" v-if="itemIndex == 1">
								<image-upload :uploadId="item.id" deletable="false" :disabled="true"
									:fileList="fileArr1" />
							</view>
							<view class="upload" v-if="itemIndex == 3">
								<image-upload :uploadId="item.id" :disabled="true" :fileList="fileArr2" />
							</view>
							<view class="upload" v-if="itemIndex == 5">
								<image-upload :uploadId="item.id" :disabled="true" :fileList="fileArr3" />
							</view>
						</view>
					</view>
					<view class="btn">
						<view class="start" data-type="开始处理" @click="handleBtn" v-if="showStart">开始处理</view>
						<view class="complete" data-type="处理完成" @click="handleBtn" v-if="showComplete">处理完成</view>
						<!-- 验证人的两个按钮 -->
						<view class="agree" data-type="同意" @click="handleBtn" v-if="showAgree">同意</view>
						<view class="reject" data-type="拒绝" @click="handleBtn" v-if="showReject">拒绝</view>
						<view class="stop" data-type="终止" @click="handleBtn" v-if="showStop">终止</view>
					</view>
				</van-tab>
			</van-tabs>
			<van-icon name="arrow-left" class="tabs-left-tip" @click="handleLeft" />
			<van-icon name="arrow" class="tabs-right-tip" @click="handleRight" />
		</view>
		<!-- 弹出拒绝的框 -->
		<van-dialog class="dialog" use-slot :show="showRejectDialog" show-cancel-button @confirm="clickSubmit"
			:before-close="beforeCloseDialog" @cancel="closeDialog">
			<view class="title">拒绝工单意见</view>
			<textarea v-if="showRejectDialog" class="areas" placeholder="请输入" id="textarea" :minlength="textareaMin"
				:maxlength="textareaMax" @input="rejectInputs">
        <text class="currentWordNumber">{{ textareaLength || 0 }}/{{ textareaMax }}</text>
        <text class="hint">{{ textareaTexts }}</text>
      </textarea>
		</van-dialog>
	</view>
</template>


<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		ref,
		computed,
		reactive,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		reqOrderDetail
	} from "@/api/operate.js"



	// 使用 ref 定义基本类型数据
	const id = ref(''); // 工单详细信息需要的 id
	const active = ref('光伏检查'); // tabs 绑定的数据
	const textareaMin = ref(1); // 拒绝原因-最少字数
	const textareaMax = ref(500); // 拒绝原因-最多字数
	const textareaTexts = ref('至少输入1个字~'); // 拒绝原因-实时输入事件
	const textareaLength = ref(null); // 拒绝原因-输入的长度
	const textareaValue = ref(''); // 拒绝原因-绑定的数据
	const remark = ref('');
	const flag = ref(true);
	const state = ref(null); // 当前状态
	const showStart = ref(false); // btn 按钮--处理人--开始处理
	const showComplete = ref(false); // btn 按钮--处理人--处理完成
	const showAgree = ref(false); // btn 按钮--验证人--同意
	const showReject = ref(false); // btn 按钮--验证人--拒绝
	const showStop = ref(false); // btn 按钮--发起人--终止
	const disabled = ref(true); // 是否禁用
	const showRejectDialog = ref(false); // 是否展示拒绝的 dialog 弹窗

	// 使用 reactive 定义对象类型数据
	const gongdanDetail = reactive({}); // 工单详情数据
	const tabsList = reactive([]); // tabs 的数据
	const fileList = reactive([]); // 图片描述绑定的数据
	const fileArrTest = reactive([{
		url: 'https://gems-pros.com/resources/file/2023/12/15/RmaKbjBQ8LK3GE5oy4Dn.png',
		id: 'NRYW68POBwd9v41A3yMw',
	}, ]);
	const fileArr1 = reactive([]);
	const fileArr2 = reactive([]);
	const fileArr3 = reactive([]);

	const getGongdanInfo = async (id) => {
		try {
			let res = await reqOrderDetail(id);
			let data = res.data.data

			Object.assign(gongdanDetail, data);
			tabsList.splice(0, tabsList.length, ...data.workorderReportList);
			active.value = data.workorderReportList[0].name;
			state.value = data.state;

			const fileArr = [];
			tabsList.forEach((tab) => {
				tab.workorderReportItemList.forEach((item) => {
					if (item.type === 1 || item.type === 2) {
						item.textareaMin = 1;
						item.textareaMax = 520;
						item.textareaTexts = '至少输入1个字~';
						item.textareaLength = item.value ? item.value.length : 0;
						if (item.textareaLength <= item.textareaMin) {
							item.textareaTexts = '至少输入1个字~';
						} else {
							item.textareaTexts = ' ';
						}
					} else if (item.type === 4 && item.value) {
						fileArr.push({
							url: item.value,
							id: item.id,
							deletable: false
						});
					}
				});
			});

			fileArr1.splice(0, fileArr1.length, fileArr[0] || {});
			fileArr2.splice(0, fileArr2.length, fileArr[1] || {});
			fileArr3.splice(0, fileArr3.length, fileArr[2] || {});

			console.log("工单tabList-->", tabsList)

			const name = tabsList[tabsList.length - 1].name;
			let userInfo = uni.getStorageSync('zh-h5-userInfo')
			const user = userInfo.userName;

			showStart.value =
				user === gongdanDetail.processor.userName && state.value === 1 && name === active.value;
			showComplete.value =
				user === gongdanDetail.processor.userName && state.value === 2 && name === active.value;
			showAgree.value =
				user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
			showReject.value =
				user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
			showStop.value =
				user === gongdanDetail.creater.userName &&
				state.value !== 5 &&
				state.value !== 8 &&
				name === active.value;
			disabled.value =
				user === gongdanDetail.processor.userName && state.value === 2 ? false : true;
		} catch (err) {
			console.error('获取工单详情数据失败，错误信息为：', err);
		}
	};


	const bindSinglelineInput = (e, id) => {
		const value = e.target.value;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
				}
			});
		});
	};


	const textareaInputs = (e, id) => {
		const value = e.target.value;
		const len = value.length;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
					item.textareaLength = len;
					item.textareaTexts = len <= item.textareaMin ? '至少输入1个字~' : ' ';
				}
			});
		});
	};


	const switchChange = (e, id) => {
		const value = e.target.checked;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
				}
			});
		});
	};

	const returnAvatar = (e, uploadId) => {
		const {
			url,
			type,
			fileList
		} = e.detail;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === uploadId) {
					item.value = type === '上传成功' ? url : fileList.length ? fileList[0].url : '';
				}
			});
		});
	};
	const onClick = (e) => {
		active.value = e.detail.name;
		const name = tabsList[tabsList.length - 1].name;
		const user = userInfo.user.userName;

		showStart.value =
			user === gongdanDetail.processor.userName && state.value === 1 && name === active.value;
		showComplete.value =
			user === gongdanDetail.processor.userName && state.value === 2 && name === active.value;
		showAgree.value =
			user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
		showReject.value =
			user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
		showStop.value =
			user === gongdanDetail.creater.userName &&
			state.value !== 5 &&
			state.value !== 8 &&
			name === active.value;
		disabled.value =
			user === gongdanDetail.processor.userName && state.value === 2 ? false : true;
	};

	const handleBtn = async (e) => {
		const type = e.currentTarget.dataset.type;

		if (type === '开始处理') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 2,
				});

				if (data.success) {
					uni.showToast({
						title: '开始处理工单',
						icon: 'none',
						duration: 2000,
					});
					getGongdanInfo();
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
				uni.showToast({
					title: err.data.message,
					icon: 'none',
					duration: 2000,
				});
			}
		} else if (type === '处理完成') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 3,
				});

				if (data.success) {
					const {
						data: reportData
					} = await httpRequest('/workorders/disposal/report', 'PUT', tabsList);

					if (reportData.success) {
						uni.showToast({
							title: '处理完成~',
							icon: 'none',
							duration: 2000,
						});
						getGongdanInfo();
					}
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		} else if (type === '终止') {
			uni.showModal({
				title: '确定要终止工单吗?',
				content: '注意：终止工单将导致该工单永久失效。',
				success: async (res) => {
					if (res.confirm) {
						try {
							const {
								data
							} = await httpRequest('/workorders/disposal', 'POST', {
								processorId: gongdanDetail.processor.userId,
								validatorId: gongdanDetail.validator.userId,
								workorderId: id.value,
								state: 8,
							});

							if (data.success) {
								uni.showToast({
									title: '终止工单成功~',
									icon: 'none',
									duration: 2000,
								});
								getGongdanInfo();
							}
						} catch (err) {
							console.error('点击接受失败，错误信息为：', err);
						}
					}
				},
			});
		} else if (type === '同意') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 5,
					operation: 1,
				});

				if (data.success) {
					uni.showToast({
						title: '通过,工单已完成~',
						icon: 'none',
						duration: 2000,
					});
					getGongdanInfo();
					uni.navigateBack({
						delta: 1,
					});
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		} else if (type === '拒绝') {
			showRejectDialog.value = true;
		}
	};

	const closeDialog = () => {
		showRejectDialog.value = false;
		remark.value = '';
		textareaLength.value = null;
	};

	const clickSubmit = async () => {
		if (remark.value === '') {
			uni.showToast({
				title: '意见不能为空~',
				icon: 'none',
				duration: 2000,
			});
			showRejectDialog.value = true;
		} else {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 1,
					operation: 0,
					remark: remark.value,
				});

				if (data.success) {
					uni.showToast({
						title: '拒绝成功~',
						icon: 'none',
						duration: 2000,
					});
					showRejectDialog.value = false;
					remark.value = '';
					textareaLength.value = null;
					getGongdanInfo();
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		}
	};
	// 输入框内容处理
	const rejectInputs = (e) => {
		const value = e.target.value;
		const len = value.length;
		remark.value = value;

		// 最少字数限制
		if (len <= textareaMin.value) {
			textareaTexts.value = '至少输入1个字~';
		} else if (len > textareaMin.value) {
			textareaTexts.value = '';
		}

		// 最多字数限制
		if (len > textareaMax.value) return;
		textareaLength.value = len; // 当前字数
	};

	// 切换到下一项
	const handleRight = () => {
		const currentIndex = tabsList.value.findIndex((item) => item.name === active.value);

		if (currentIndex !== -1 && currentIndex < tabsList.value.length - 1) {
			active.value = tabsList.value[currentIndex + 1].name;
		} else {
			uni.showToast({
				title: '已经是最后一项了',
				icon: 'none',
				duration: 2000,
			});
		}
	};

	// 切换到上一项
	const handleLeft = () => {
		const currentIndex = tabsList.value.findIndex((item) => item.name === active.value);

		if (currentIndex > 0) {
			active.value = tabsList.value[currentIndex - 1].name;
		} else {
			uni.showToast({
				title: '已经是第一项了',
				icon: 'none',
				duration: 2000,
			});
		}
	};


	onMounted(() => {
		// getGongdanInfo();
	});
	onLoad((option) => {
		const instance = getCurrentInstance().proxy;
		const eventChannel = instance.getOpenerEventChannel()
		getGongdanInfo(option.id)
		// eventChannel.on('getAlarmId', (data) => {
		// 	getDetail(option.alarmId)
		// })

	})
</script>

<style lang="scss" scoped>


</style>